package com.dianjing.dianqun.common.base;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestParam;

import com.dianjing.dianqun.common.ResponseData;
import com.dianjing.dianqun.model.SiteFlow;
import com.dianjing.dianqun.model.dto.UserDTO;
import com.dianjing.dianqun.service.SiteFlowService;
import com.dianjing.dianqun.service.UserService;
import com.dianjing.dianqun.utils.IPSeeker;
import com.dianjing.dianqun.utils.IPSeeker.IPLocation;
import com.dianjing.dianqun.utils.StringUtils;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * 所有异常都要要try  以免 不知道错误信息 返回数据失败 
 * @see 2017-09-27
 * @author baoyongtao
 *
 */
@ComponentScan
public abstract class BaseRestController {

	protected final static Logger LOG = LoggerFactory.getLogger(BaseRestController.class);
	
	
	@Autowired
	private SiteFlowService flowService;
	
	@Autowired
	private UserService userService;
	
	private static IPSeeker seeker ;
	
	public static ObjectMapper mapper;
	static {
		mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Include.NON_EMPTY);
		seeker=new IPSeeker();
	}

	/**
	 * 保存最近访客  需要自己判断条件是否保存 
	 * @param userId
	 * @param request
	 */
	public boolean saveSiteFlow(Integer siteId,Integer userId,HttpServletRequest request) {
		Date date = new Date();
		SiteFlow siteFlow = new SiteFlow();
		if(userId!=null) {
			siteFlow.setUserId(userId);
		}
		siteFlow.setAccessDate(DateFormatUtils.format(date, "yyyy-MM-dd hh:mm:ss"));
		siteFlow.setAccessIp(StringUtils.getRemoteAddr(request));
		siteFlow.setAccessTime(date);
		siteFlow.setSiteId(siteId);
		siteFlow.setAccessPage(request.getRequestURL().toString());//目标页面
		siteFlow.setRefererPage(request.getHeader("referer"));
		IPLocation ipLocation = seeker.getIpLocation(StringUtils.getRemoteAddr(request));//ip解析
		siteFlow.setArea(ipLocation.getCountry());//地区
		siteFlow.setSessionId(SecurityUtils.getSubject().getSession().getId().toString());
		try {
			flowService.insertSelective(siteFlow);
		} catch (Exception e) {
			return false;
		}
		LOG.info("save  site flow ok ");
		return true;
	}
	
	

	/**
	 * 客户端返回JSON字符串
	 * 
	 * @param response
	 *            可以采用注解来返回json数据格式
	 *            0
	 * @param object
	 * @return
	 */

	protected String renderString(HttpServletResponse response, Object object) {
		String json = null;
		try {
			json = mapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return renderString(response, json, "application/json");
	}

	/**
	 * 客户端返回字符串
	 * 
	 * @param response
	 * @param string
	 * @return
	 */
	protected String renderString(HttpServletResponse response, String string, String type) {
		try {
			response.reset();
			response.setContentType(type);
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
			return null;
		} catch (IOException e) {
			return null;
		}
	}
	protected Integer convertUserId(Integer userId) {
		UserDTO convertUser = userService.convertUser(userId);
		return convertUser==null?null:convertUser.getUserId();
	}
	
}